const moment = require("moment");
const { Op } = require("sequelize");
let TEST = false;
// TEST = true;

module.exports = function (app, opts) {
  const synchronizeWorkOrder = app.fs.scheduleInit(
    {
      interval: "0 5 * * * *", //每小时的05分触发定时任务
      immediate: false,
      // proRun: !TEST,
    },
    async () => {
      try {
        console.log("工单数据开始同步", moment().format("YYYY-MM-DD HH:mm:ss"));
        const { models } = app.fs.dc;
        const sequelize = app.fs.dc.orm;
        const existingData = await models.WorkOrderManagement.findAll({
          attributes: ["abnormalTypeId", "recordId"],
        });
        //abnormalTypeId=1,非计划性，abnormalTypeId=2计划性
        //计划性检修记录
        const planPatrolRecords =
          await models.PlannedPatrolRecordDetail.findAll({
            include: [
              {
                model: models.PlannedPatrolRecord,
                required: true,
                attributes: [
                  "id",
                  [
                    sequelize.literal(
                      `"plannedPatrolRecord"."user_info"->'user'->'department'->>'name'`
                    ),
                    "departmentName",
                  ],
                  "inspectionTime",
                ],
                include: [
                  {
                    model: models.Project,
                    required: true,
                    attributes: ["id", "name"],
                  },
                ],
              },
              {
                model: models.PlannedCheckItems,
                required: true,
                attributes: ["id", "name"],
              },
            ],
            where: {
              alarm: true,
            },
            attributes: ["id", "userName", "imgs", "msgInp"],
          });
        //非计划性任务检修记录(不考虑养护管理)
        const unplannedPatrolRecords =
          await models.UnplannedRecordCheckItems.findAll({
            attributes: ["id", "imgUpload"],
            include: [
              {
                model: models.UnplannedRecordTemplates,
                required: true,
                include: [
                  {
                    model: models.UnplannedPatrolRecord,
                    required: true,
                    attributes: ["id", "completeTime"],
                  },
                ],
                attributes: ["id"],
              },
              {
                model: models.UnplannedPatrolPlan,
                attributes: ["id"],
                required: true,
                where: {
                  status: 2, //代表已经做完了
                },
                include: [
                  {
                    model: models.User,
                    attributes: ["id", "name"],
                    required: true,
                    include: [
                      {
                        model: models.Department,
                        attributes: ["id", "name"],
                        required: true,
                      },
                    ],
                  },
                  {
                    model: models.Project,
                    attributes: ["id", "name"],
                    required: true,
                  },
                ],
              },
              {
                model: models.UnplannedCheckItems,
                attributes: ["id", "name"],
                required: true,
              },
              {
                model: models.UnplannedPatrolTemplate,
                as: "rtemplates",
                attributes: ["id"],
                where: {
                  workType: 2, //去掉养护部分
                },
              },
            ],
            where: {
              alarm: true,
            },
          });
        let filterPlanPatrolRecords = [];
        for (let i = 0; i < planPatrolRecords.length; i++) {
          let curItem = planPatrolRecords[i];
          if (
            !existingData.some(
              (item) =>
                item.recordId === curItem.id && item.abnormalTypeId === 2
            )
          ) {
            let insertItem = {
              recordId: curItem.id,
              abnormalTypeId: 2,
              applyDepartment:
                ((curItem.plannedPatrolRecord || {}).dataValues || {})
                  .departmentName || "-",
              abnormalTitle:
                ((curItem.plannedPatrolRecord || {}).project || {}).name || "-",
              applyUser: curItem.userName || "-",
              abnormalDetail: (curItem.plannedCheckItem || {}).name || "-",
              abnormalImgs: curItem.imgs || [],
              createTime: moment(
                (curItem.plannedPatrolRecord || {}).inspectionTime
              ).format("YYYY-MM-DD HH:mm:ss"),
              status: 1,
              inspectionDetails: curItem.msgInp || "-",
            };
            filterPlanPatrolRecords.push(insertItem);
          }
        }
        for (let i = 0; i < unplannedPatrolRecords.length; i++) {
          let curItem = unplannedPatrolRecords[i];
          if (
            !existingData.some(
              (item) =>
                item.recordId === curItem.id && item.abnormalTypeId === 1
            )
          ) {
            let insertItem = {
              recordId: curItem.id,
              abnormalTypeId: 1,
              applyDepartment:
                ((curItem.unplannedPatrolPlan || {}).users[0] &&
                  (
                    (curItem.unplannedPatrolPlan || {}).users[0].department ||
                    {}
                  ).name) ||
                "-",
              abnormalTitle:
                ((curItem.unplannedPatrolPlan || {}).project || {}).name || "-",
              applyUser:
                ((curItem.unplannedPatrolPlan || {}).users || [])
                  .map((u) => u.name)
                  .join(",") || "-",
              abnormalDetail: (curItem.unplannedCheckItem || {}).name || "-",
              abnormalImgs: curItem.imgUpload || [],
              createTime: moment(
                (
                  (
                    ((curItem.unplannedRecordTemplate || {}).dataValues || {})
                      .unplannedPatrolRecord || {}
                  ).dataValues || {}
                ).completeTime
              ).format("YYYY-MM-DD HH:mm:ss"),
              status: 1,
            };
            filterPlanPatrolRecords.push(insertItem);
          }
        }
        if (filterPlanPatrolRecords.length) {
          await models.WorkOrderManagement.bulkCreate(filterPlanPatrolRecords);
        }
        console.log("工单数据同步检修记录", filterPlanPatrolRecords.length);
        console.log("工单数据同步结束", moment().format("YYYY-MM-DD HH:mm:ss"));
      } catch (error) {
        console.error("Error in synchronizeWorkOrder:", error);
        app.fs.logger.error(`schedule: synchronizeWorkOrder, error: ${error}`);
      }
    }
  );

  return {
    synchronizeWorkOrder,
  };
};
